package practise;

public class EvalRPN {
    public static void main(String[] args) {
        String[] s = {"4","13","5","/","+"};
        evalRPN(s);
    }
    private static boolean isDigit(String s) {
        try {
            Integer.parseInt(s);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public static int evalRPN(String[] tokens) {
        int len = tokens.length;
        int[] stack = new int[len];
        int useSize = 0;
        String s;
        for (int i = 0; i < len; i++) {
            s = tokens[i];
            if(isDigit(s)) {
                stack[useSize++] = Integer.parseInt(s);
            } else {
                int n2 = stack[--useSize];
                int n1 = stack[--useSize];
                switch (s) {
                    case "+" :
                        stack[useSize++] = n1 + n2;
                        break;
                    case "-" :
                        stack[useSize++] = n1 - n2;
                        break;
                    case "*" :
                        stack[useSize++] = n1 * n2;
                        break;
                    case "/" :
                        stack[useSize++] = n1 / n2;
                        break;
                }
            }
        }
        return stack[0];
    }
}
